<template>
    <div style="width: 100%;margin-top: -20px;background-color: white">
        <div class="avatar-box">
            <div @click="closeWindow" class="back-arrow">
                <i class="el-icon-arrow-left"/>
            </div>
            <div v-if="unread!==0" class="unread-num">
                {{ unread }}
            </div>

            <el-avatar style="padding: 2px;background-color: white"
                       :size="48" :src="avImg"></el-avatar>
            <div style="display: flex;flex-direction: column;margin-left: 20px">
                <div style="font-weight: bold;font-family: Poppins">
                    {{ chatinfo.users.userName }}
                </div>
                <div style="display: flex;align-items: center;margin-top: 5px">
                    <div style="border-radius: 50px;width:10px;height: 10px;background-color: #34c38f"/>

                    <div style="color: #788294;font-size: 14px;margin-left: 5px">
                        Active now
                    </div>
                </div>
            </div>
        </div>
        <div class="message-box" ref="messageBox">
            <ChatMessage v-bind="$attrs" v-on="$listeners" v-for="(item,index) in chatinfo.todayMessage" :key="index"
                         :message="item"/>
        </div>
        <div class="send-box-wrapper">
            <div style="width: 100%;margin-top: 20px;margin-bottom: 5px;">
                <div style="display: flex">
                    <el-upload
                        action="#"
                        class="upload-demo"
                        :show-file-list="false"
                        :http-request="upload1"
                    >
                        <el-button class="el-icon-microphone file-button" size="small" type="primary"></el-button>
                    </el-upload>
                    <el-upload
                        action="#"
                        class="upload-demo"
                        :show-file-list="false"
                        :http-request="upload2"
                    >
                        <el-button class="el-icon-picture-outline file-button" size="small" type="primary"></el-button>
                    </el-upload>
                    <el-upload
                        action="#"
                        class="upload-demo"
                        :show-file-list="false"
                        :http-request="upload3"
                    >
                        <el-button class="el-icon-folder file-button" size="small" type="primary"></el-button>
                    </el-upload>
                    <el-progress style="width: 100%" v-if="progressFlag" :percentage="progressPercent"/>
                </div>


            </div>
        </div>
        <div style="display: flex;width: 100%;height: 100%;align-items: center;">
            <div class="send-box">
                <el-input v-model="inputMessage" class="message-input" placeholder="Enter messages"/>
            </div>
            <div class="send-button " @click="sendMessage">

                <div class="el-icon-s-promotion"></div>
            </div>
        </div>
    </div>

</template>

<script>
import ChatMessage from "@/components/Chat/ChatMessage";
import moment from "moment";
import axios from "axios";

export default {
    name: "ChatRoom",
    components: {ChatMessage},
    props: ['chatinfo', 'unread'],
    data() {
        return {
            userid: -1,
            avImg: require("@/assets/icon/3.png"),
            inputMessage: "",
            socket: {},
            progressPercent: 0,
            progressFlag: false,

        }
    },
    methods: {
        closeWindow() {
            this.$emit("togglePage", "chatmain", "back")
            this.$emit("setCurrentChatUserId", -1)
        },
        sendMessage() {
            const a = {
                "msgId": null,
                "msgUrl": null,
                "msgFrom": this.userid,
                "msgTo": this.chatinfo.users.userId,
                "msgContent": this.inputMessage,
                "msgTime": moment().format("YYYY-MM-DD HH:mm:ss"),
                "msgType": "Text",
                "msgGroupId": null,
                "msgRead": 0,
            }
            this.socket.send(JSON.stringify(a));
            this.inputMessage = ""
            console.log(this.chatinfo)
            this.chatinfo.todayMessage.push(a)
            this.scrollBottom()
            this.$emit("refreshMessage")
        },
        sendFile(type, url, filename) {
            const a = {
                "msgId": null,
                "msgUrl": url,
                "msgFrom": this.userid,
                "msgTo": this.chatinfo.users.userId,
                "msgContent": filename,
                "msgTime": moment().format("YYYY-MM-DD HH:mm:ss"),
                "msgType": type,
                "msgGroupId": null,
                "msgRead": 0,
            }
            this.socket.send(JSON.stringify(a));
            console.log(this.chatinfo)
            this.chatinfo.todayMessage.push(a)
            this.scrollBottom()
            this.$emit("refreshMessage")
        },
        receiveMessage(msg) {

            this.chatinfo.todayMessage.push(msg)
            this.scrollBottom()
        },
        scrollBottom() {
            var div = this.$refs.messageBox;

            //此时必须异步执行滚动条滑动至底部
            setTimeout(() => {
                div.scrollTop = div.scrollHeight;
            }, 0)
        },
        upload1(f) {
            console.log(f)
            this.progressFlag = true
            let formdata = new FormData()
            formdata.append('file', f.file)
            axios({
                url: "http://localhost:10007" + '/chat/uploadAudio',
                method: 'post',
                data: formdata,
                headers: {'Content-Type': 'multipart/form-data'},
                onUploadProgress: progressEvent => {
                    // progressEvent.loaded:已上传文件大小
                    // progressEvent.total:被上传文件的总大小
                    this.progressPercent = (progressEvent.loaded / progressEvent.total * 100)
                }
            }).then(res => {
                console.log(res.data.obj)
                var url = res.data.obj.url
                var filename = res.data.obj.filename
                if (this.progressPercent === 100) {
                    this.progressFlag = false
                    this.progressPercent = 0
                }
                this.sendFile("Audio", url, filename)
                console.log(url)
            })
        },
        upload2(f) {
            console.log(f)
            this.progressFlag = true
            let formdata = new FormData()
            formdata.append('file', f.file)
            axios({
                url: "http://localhost:10007" + '/chat/uploadFile',
                method: 'post',
                data: formdata,
                headers: {'Content-Type': 'multipart/form-data'},
                onUploadProgress: progressEvent => {
                    // progressEvent.loaded:已上传文件大小
                    // progressEvent.total:被上传文件的总大小
                    this.progressPercent = (progressEvent.loaded / progressEvent.total * 100)
                }
            }).then(res => {
                console.log(res.data.obj)
                var url = res.data.obj.url
                var filename = res.data.obj.filename
                if (this.progressPercent === 100) {
                    this.progressFlag = false
                    this.progressPercent = 0
                }
                this.sendFile("Image", url, filename)
                console.log(url)
            })
        },
        upload3(f) {
            console.log(f)
            this.progressFlag = true
            let formdata = new FormData()
            formdata.append('file', f.file)
            axios({
                url: "http://localhost:10007" + '/chat/uploadFile',
                method: 'post',
                data: formdata,
                headers: {'Content-Type': 'multipart/form-data'},
                onUploadProgress: progressEvent => {
                    // progressEvent.loaded:已上传文件大小
                    // progressEvent.total:被上传文件的总大小
                    this.progressPercent = (progressEvent.loaded / progressEvent.total * 100)
                }
            }).then(res => {
                console.log(res.data.obj)
                var url = res.data.obj.url
                var filename = res.data.obj.filename
                if (this.progressPercent === 100) {
                    this.progressFlag = false
                    this.progressPercent = 0
                }
                this.sendFile("File", url, filename)
                console.log(url)
            })
        }

    },
    mounted() {
        console.log('chat room mounted', this.chatinfo)
        if (this.$store.getters.isConnected) {
            this.socket = this.$store.getters.getWebsocket
        }
        const id = this.$store.getters.getUser.id;
        this.userid = id;
        this.scrollBottom()
        var l = []
        this.chatinfo.todayMessage.forEach(ii => {
            l.push(ii.msgId)
        })
        this.$axios.post("/chat/chat/setMessageRead", l).then(e => {
            console.log(e)
            this.$emit("refreshMessage")
        })
    }
}
</script>

<style scoped>
.avatar-box {
    background-color: white;
    width: 100%;
    display: flex;
    align-items: center;
    padding-top: 10px;;
    padding-bottom: 10px;
    padding-left: 30px;
    border-bottom: #e8e5e5 1px solid;
}

.back-arrow {
    font-size: 30px;
    line-height: 30px;
    cursor: pointer;
    transition: all ease-in-out 300ms;

}

.back-arrow:hover {
    color: #6DBEF8;
}

.message-box {

    height: 560px;
    padding-left: 25px;
    padding-right: 25px;
    overflow-y: auto;
    background-color: white;


}

.send-box-wrapper {
    padding-left: 20px;
    padding-right: 20px;
    display: flex;
    align-items: center;
    flex-direction: column;
    background-color: white;
    border-top: #e3e3e3 1px solid;
    padding-bottom: 20px;


}

.send-box {

    background-color: #eff2f7;
    height: 40px;
    width: 100%;
    border-radius: 15px;
}

.send-button {
    margin-left: 10px;
    width: 40px;
    height: 40px;
    border-radius: 30px;
    font-size: 24px;
    text-align: center;
    color: white;
    background-color: #556ee6;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all ease-in-out 300ms;
    box-shadow: 0px 1px 5px 0px rgba(0, 0, 0, 0.2);

}

.send-button:hover {
    background-color: #6DBEF8;

}

.send-button:focus {
    background-color: white;
}

.message-input >>> .el-input__inner {
    -moz-appearance: none;
    font-size: 16px;
    background-color: #eff2f7;
    border-radius: 20px;
    border: none;
    color: #313131;
    outline: 0;

}

.file-button {
    margin-left: 5px;
    font-size: 22px;
    transition: all ease-in-out 300ms;
    color: #000000;
    background-color: white;
    border: none;
    padding: 0;
}

.file-button:hover {
    background-color: white;
    color: #556ee6;
}

.file-button {

}

.unread-num {
    background-color: coral;
    color: white;
    border-radius: 50px;
    min-width: 25px;
    text-align: center;
    line-height: 27px;
    height: 25px;
    margin-right: 10px;
    margin-top: -5px;
    transition: all ease-in-out 300ms;
    animation: bounceIn;
}
</style>